import CryptoService from "@/utils/cryptoTs";

const parseData = (data) => {
    if (data) {
        return JSON.parse(JSON.stringify(data));
    }
};
const getTimeStamp = () => {
    return dateFmt('yyyyMMddSS', new Date());
};
const getFileNameAndType = (file) => {
    const fileIndex = file.lastIndexOf(".");//取到文件名开始到最后一个点的长度
    const fileNameLength = file.length;//取到文件名长度
    const fileType = file.substring(fileIndex + 1, fileNameLength);
    const fileName = file.substring(0, fileIndex);
    return {
        fileType,
        fileName
    }
};

const dateFmt = (fmt, date) => {
    const o = {
        'M+': date.getMonth() + 1,                 // 月份
        'd+': date.getDate(),                    // 日
        'h+': date.getHours(),                   // 小时
        'm+': date.getMinutes(),                 // 分
        's+': date.getSeconds(),                 // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds()             // 毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {

            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
    }
    return fmt;
};
const setCookie = (name, value, day) => {
    if (day !== 0) {     // 当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
        const expires = day * 24 * 60 * 60 * 1000;
        const date = new Date(+new Date() + expires);
        document.cookie = name + '=' + escape(value) + ';expires=' + date.toUTCString();
    } else {
        document.cookie = name + '=' + escape(value);
    }
};

const getCookie = (name) => {
    let c_start;
    let c_end;
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(name + '=');
        if (c_start !== -1) {
            c_start = c_start + name.length + 1;
            c_end = document.cookie.indexOf(';', c_start);
            if (c_end === -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return '';
};
const convertKey = (arr, key) => {
    const newArr = [];
    arr.forEach((item) => {
        const newObj = {};
        for (let i = 0; i < key.length; i++) {
            newObj[key[i]] = item[Object.keys(item)[i]];
        }
        newArr.push(newObj);
    });
    return newArr;
};
const getDateString = (stamp) => {
    let d = new Date(parseInt(stamp));
    let month = (d.getMonth() + 1) < 10 ? (0 + "" + (d.getMonth() + 1)) : (d.getMonth() + 1);
    let day = d.getDate() < 10 ? (0 + "" + d.getDate()) : d.getDate();
    let hour = d.getHours() < 10 ? (0 + "" + d.getHours()) : d.getHours();
    let minute = d.getMinutes() < 10 ? (0 + "" + d.getMinutes()) : d.getMinutes();
    let second = d.getSeconds() < 10 ? (0 + "" + d.getSeconds()) : d.getSeconds();
    let dateString = d.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
    return dateString;
};

const deepClone=(obj)=> {
    const objClone = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === 'object') {
        for (const key in obj) {
            // 判断ojb子元素是否为对象，如果是，递归复制
            if (obj[key] && typeof obj[key] === 'object') {
                objClone[key] = deepClone(obj[key]);
            } else {
                // 如果不是，简单复制
                objClone[key] = obj[key];
            }
        }
    }
    return objClone;
};
/**
 * 分类翻译
 */
const findLabelByKey = (type, key, num)=> {
    let originalClassList = '';
    if (type === 0) {
        originalClassList = JSON.parse(localStorage.getItem('originalClassList'));
    } else {
        originalClassList = JSON.parse(localStorage.getItem('publishingClassList'));
    }
    let className = '';
    if (num === 1) {
        originalClassList.map((item) => {
            if (item.value === key) {
                className = item.label
            }
        })
    } else {
        originalClassList.map((item) => {
            item.children.map((_item) => {
                if (_item.value === key) {
                    className = _item.label
                }
            })
        })
    }
    return className
};
const testFileName = (type, file) =>{
    const names = file.name.split('.');
    const typeReg = new RegExp(type.replace(new RegExp('/', 'g'), '|'));
    return typeReg.test(`.${names[names.length - 1]}`);
};
/**
 * 是否独家转换
 */
const isExclusive=(value)=>{
    if(value){
        return '是'
    }else{
        return '否'
    }
};
/**
 * 时间戳转还xxxx-xx-xx
 */
const ultZeroize = (v, l) => {
    var z = "";
    l = l || 2;
    v = String(v);
    for (var i = 0; i < l - v.length; i++) {
        z += "0";
    }
    return z + v;
};
const time= (d)=>{
    if (typeof (d) == "string") d = new Date(d * 1000);
    return (d.getFullYear() + "-" + ultZeroize(d.getMonth() + 1) + "-" + ultZeroize(d.getDate()));
};
// MinIo配置
const getMinIoConfig =  () =>{
    if (sessionStorage.getItem('userInfo')) {
        var minioConfig = JSON.parse(sessionStorage.getItem('userInfo')).minioConfig
        return {
            // 解密
            accessKey: CryptoService.decrypt(minioConfig.accessKey),
            secretKey: CryptoService.decrypt(minioConfig.secretKey),
            bucket: CryptoService.decrypt(minioConfig.bucket),
            url: CryptoService.decrypt(minioConfig.url)
        };
    } else {
        return {
            accessKeyId: CryptoService.decrypt('5n5g5frS0rRLfQn+qxQ1yQ=='),
            accessKeySecret: CryptoService.decrypt('qcC2P662sgZ5S2nx71I0oQ=='),
            bucket: CryptoService.decrypt('9iYLlCOzjl+Twj2hJAvwUA=='),
            region: CryptoService.decrypt('VJGBDiHLsL7+kOMCD6qPSWmGNiWTIHXktY/ioMyf0Vo=')
        };
    }
};
const getMinioPath = ()=>{
    if (sessionStorage.getItem('minioConfig')) {
        var minioConfig = JSON.parse(sessionStorage.getItem('minioConfig'))
        return CryptoService.decrypt(minioConfig.url)
    }
}
export default {
    parseData,
    getFileNameAndType,
    dateFmt,
    setCookie,
    getCookie,
    getDateString,
    getTimeStamp,
    convertKey,
    deepClone,
    findLabelByKey,
    testFileName,
    isExclusive,
    time,getMinIoConfig,getMinioPath

}
